package com.mstanford.movie.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mstanford.movie.dao.MovieDao;
import com.mstanford.movie.utils.DataUtil;

public class QueryMovieServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String movieName = request.getParameter("movieName");
		String type = request.getParameter("type");
		String today = request.getParameter("today");
		String pageId = request.getParameter("pageId");
		String pageSize = request.getParameter("pageSize");
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("movieName", movieName);
		map.put("type", type);
		map.put("date", today);
		map.put("pageId", pageId);
		map.put("pageSize", pageSize);
		
		MovieDao dao = new MovieDao();
		dao.queryMovieByDateCount(map);
		DataUtil.buildPagingMap(map);
		List<Map<String, String>> list = dao.queryMovieByDate(map);
		
		String pageJson = DataUtil.mapToJson(map);
		String dataJson = DataUtil.listToJson(list);
		
		String json = "{\"page\":" + pageJson + ",\"data\":" + dataJson + "}";

		response.setContentType("application/json; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.print(json);
		out.flush();
		out.close();
	}
}